<template>
  <el-table :data="formData" class="-mt-10px">
    <el-table-column label="序号" type="index" width="100"/>
    <el-table-column label="条码" min-width="150">
      <!--        &lt;!&ndash; 条码输入框 &#45;&#45;barcode>-->
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.barCode`" class="mb-0px!">
          <el-input
            v-model="row.barCode"
            placeholder="点击搜索选择条码"
            suffix-icon="el-icon-search"
            @click="dialogVisible=true"
            width="800px"
          />
        </el-form-item>
      </template>

    </el-table-column>


    <el-table-column label="货物名称" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.gname`" class="mb-0px!">
          <el-input v-model="row.gname" placeholder="请输入货物名称"/>
        </el-form-item>
      </template>
    </el-table-column>

    <el-table-column label="数量" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.number`" :rules="formRules.number" class="mb-0px!">
          <el-input v-model="row.number" placeholder="请输入数量"/>
        </el-form-item>
      </template>
    </el-table-column>

    <el-table-column label="类型" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.productType`" class="mb-0px!">
          <el-select v-model="row.productType" placeholder="请选择商品类型">
            <el-option label="请选择字典生成" value=""/>
          </el-select>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column label="类别" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.category`" class="mb-0px!">
          <el-input v-model="row.category" placeholder="请输入类别"/>
        </el-form-item>
      </template>
    </el-table-column>

    <el-table-column label="型号" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.model`" class="mb-0px!">
          <el-input v-model="row.model" placeholder="请输入型号"/>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column label="品牌" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.brand`" class="mb-0px!">
          <el-input v-model="row.brand" placeholder="请输入品牌"/>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column label="单位" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.unit`" class="mb-0px!">
          <el-input v-model="row.unit" placeholder="请输入单位"/>
        </el-form-item>
      </template>
    </el-table-column>


    <el-table-column label="规格" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.specif`" class="mb-0px!">
          <el-input v-model="row.specif" placeholder="请输入规格"/>
        </el-form-item>
      </template>
    </el-table-column>

    <el-table-column label="用途" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.type`" class="mb-0px!">
          <el-input v-model="row.type" placeholder="请输入1—备货"/>
        </el-form-item>
      </template>
    </el-table-column>

    <el-table-column label="主要技术参数" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.technicalParameter`" class="mb-0px!">
          <el-input v-model="row.technicalParameter" placeholder="请输入主要技术参数"/>
        </el-form-item>
      </template>
    </el-table-column>

    <el-table-column label="备注" min-width="150">
      <template #default="{ row, $index }">
        <el-form-item :prop="`${$index}.notes`" class="mb-0px!">
          <el-input v-model="row.notes" placeholder="请输入备注"/>
        </el-form-item>
      </template>
    </el-table-column>

    <el-table-column align="center" fixed="right" label="操作" width="60">
      <template #default="{ $index }">
        <el-button @click="handleDelete($index)" link>—</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加项目物资申请单</el-button>
  </el-row>

  <!-- 商品选择对话框 -->
  <el-dialog
v-model="dialogVisible" title="商品搜索" width="72%" :style="{ height: '85%' }"
             :modal="true" :append-to-body="true">
    <!--    <div style="display: flex; flex-direction: column; height: 100%;">-->

    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParamsGoods"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="商品" prop="documentNumber">
          <el-input
            v-model="queryParamsGoods.barCode"
            placeholder="请输入商品名称或条码"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>

        <!--      类型（1-项目，3办公室，2零星，4销售，5采购）-->
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="queryParamsGoods.type"
            placeholder="请选择类型"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.ERP_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px"/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px"/>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <el-scrollbar height="400px">
      <!-- 设置高度为600px -->
      <el-table
:data="listProduct" v-model="selectedRows"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="(row) => !row.noOpera" width="55"/>
        <el-table-column label="条码" align="center" prop="barCode"/>
        <el-table-column label="货物名称" align="center" prop="gname"/>
        <el-table-column label="商品类型" align="center" prop="productType"/>
        <el-table-column label="类别" align="center" prop="category"/>
        <el-table-column label="型号" align="center" prop="model"/>
        <el-table-column label="品牌" align="center" prop="brand"/>
        <el-table-column label="单位" align="center" prop="unit"/>
        <el-table-column label="规格" align="center" prop="specif"/>
        <el-table-column label="状态(启用)" align="center" prop="stats"/>
        <el-table-column label="用途" align="center" prop="type"/>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
      </el-table>
    </el-scrollbar>
    <template #footer>
      <el-row>
        <el-col :span="9" :offset="15"> <!-- 分页插件占用左边空间 -->
          <Pagination
            :total="total"
            v-model:page="queryParamsGoods.pageNo"
            v-model:limit="queryParamsGoods.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5" :offset="19">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="selectGoodsConfirm">确定</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {MaterialDemandApi} from '@/api/werp/purchase/materialdemand'
import {ref} from 'vue';
import { DICT_TYPE, getIntDictOptions } from "@/utils/dict";
import {CommodityInfoApi} from "@/api/material/commodityinfo";
import {dateFormatter} from "@/utils/formatTime";

export interface CommodityInfoVO {
  id: number // 商品信息id标识
  sonId: string // 子件id
  barCode: string // 条码
  productType: string // 商品类型
  category: string // 类别
  gname: string // 货物名称
  model: string // 型号
  brand: string // 品牌
  unit: string // 单位
  stats: number // 状态(1启用)
  type: string // (1项目，2办公)
  isBatchnumber: number // (1有 2没有)
  describe: string // 描述
  specif: string // 规格
  isSplit: string // 是否可拆分（1是2否）
  documentNumber: string // 单据编号
  documentDate: string // 单据日期
}

const props = defineProps<{
  documentNumber: {
    type: String|undefined, // 确保类型
    required: true,
  },
  id?: number|String// 单据编号（主表的关联字段）
  type?: String | undefined // 单据类型（主表的关联字段）
}>();


let queryParamsGoods = reactive({
  pageNo: 1,
  pageSize: 10,
  sonId: undefined,
  barCode: undefined,
  productType: undefined,
  category: undefined,
  gname: undefined,
  model: undefined,
  brand: undefined,
  unit: undefined,
  stats: undefined,
  isBatchnumber: undefined,
  describe: undefined,
  specif: undefined,
  isSplit: undefined,
  createTime: [],
  documentNumber: String,
  type: undefined,
})


const formLoading = ref(false) // 表单的加载中
const formData = ref<CommodityInfoVO[]>([]); // 正确设置 formData 的类型
const formRef = ref() // 表单 Ref


// 定义验证规则barCode category gname
const formRules = {
  documentDate: [
    {required: true, message: '请选择单据日期', trigger: 'change'}
  ],
  barCode: [
    {required: true, message: '请输入条码', trigger: 'blur'}
  ],
  gname: [
    {required: true, message: '请输入货物名称', trigger: 'blur'}
  ],
  number: [ // 数量
    {required: true, message: '请输入数量', trigger: 'blur'},

  ],

};



/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(() => props.documentNumber,async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val||typeof val === 'function') {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await MaterialDemandApi.getProjectOrderListByDocumentNumber(val)
 
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

const handleAdd = () => {
  const row = {} as CommodityInfoVO
  console.log('formData', formData.value)
  formData.value.push(row); // 此处不再爆红
};


/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}


/** 表单值 */
const getData = () => {
  return formData.value
}
defineExpose({validate, getData})

const dialogVisible = ref(false);
const loading = ref(false);


// const route = useRoute()
onMounted(async () => {
  console.log('documentNumber in child12131:', props.documentNumber);
  handleQuery()
})


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParamsGoods.pageNo = 1
  getList()
}
const listProduct = ref<CommodityInfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const getList = async () => {
  loading.value = true
  try {
    const data = await CommodityInfoApi.getCommodityInfoPage(queryParamsGoods)
    listProduct.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  Object.keys(queryParamsGoods).forEach(key => {
    queryParamsGoods[key] = undefined;
  });
  getList()
}


const selectedRows = ref([]); // 存储选中的商品
const selectGoodsConfirm = () => {
  formData.value = formData.value.filter(item => Object.keys(item).length > 0);
  formData.value.push(...selectedRows.value)
  console.log('cesh', formData.value)
  dialogVisible.value = false;

}

const handleSelectionChange = (val) => {
  selectedRows.value = val; // 收集选择的商品
};
</script>
<style scoped>
.custom-input {
  width: 185px;
  height: 32px;
}
</style>
